package com.awakening.o2o.config.dao;

import com.awakening.o2o.util.DESUtil;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * 配置DataSource到IOC容器里面
 * 配置mybatis mapper的扫描路径
 * @Author:AwakeningCode
 * @Date: Created in 22:01 2018\2\2 0002
 */
@Configuration
@MapperScan("com.awakening.o2o.dao")
public class DataSourceConfiguration {

    private final Logger logger = LoggerFactory.getLogger(DataSourceConfiguration.class);

    @Value("${jdbc.driver}")
    private String jdbcDriver;

    @Value("${jdbc.url}")
    private String jdbcUrl;

    @Value("${jdbc.username}")
    private String jdbcUsername;

    @Value("${jdbc.password}")
    private String jdbcPassword;

    /**
     * 生成与spring-dao.xml对应的bean dataSource
     * @return
     */
    @Bean(name = "dataSource")
    public ComboPooledDataSource createDataSource(){
        //生成dataSource实例
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        try {
            //驱动
            dataSource.setDriverClass(jdbcDriver);
            //数据库连接
            dataSource.setJdbcUrl(jdbcUrl);
            //数据库用户名
            dataSource.setUser(DESUtil.getDecryptString(jdbcUsername));
            //数据库密码
            dataSource.setPassword(DESUtil.getDecryptString(jdbcPassword));
            //连接池最大线程数
            dataSource.setMaxPoolSize(30);
            //连接池最小线程数
            dataSource.setMinPoolSize(10);
            //关闭连接后不自动commit
            dataSource.setAutoCommitOnClose(false);
            //连接超时时间
            dataSource.setCheckoutTimeout(10000);
            //连接失败重试次数
            dataSource.setAcquireRetryAttempts(2);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return dataSource;
    }

}
